<template>
  <div class="tablelist">
    <el-dialog
      class="father"
      :title="state ? '修改商品属性' : '添加商品属性'"
      :visible.sync="dialogFormVisible"
      width="100%"
      top="0"
      :before-close="cancel"
    >
      <el-form
        :model="submitData"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="upload-wrapper flex-col-24">
          <span>规格图片</span>
          <div class="upload-box">
            <el-upload
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :multiple="false"
              :on-change="uploadFile"
              drag
              accept="image/jpg,image/jpeg,image/png"
            >
              <i
                v-if="imageUrl"
                class="el-icon-circle-close deleteImg"
                @click.stop="handleRemove"
              ></i>
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="el-upload--picture-car"
                style="width: 300px; height: 300px"
              />
              <div
                style="
                  display: flex;
                  align-item: center;
                  flex-direction: column;
                  justify-content: center;
                  background-color: var(--bg-primary-color);
                  height: 100%;
                "
                v-else
              >
                <i
                  class="el-icon-picture"
                  style="font-size: 40px; color: #d9d9d9"
                ></i>
              </div>
            </el-upload>
            <el-button
              class="send"
              plain
              type="primary"
              size="small"
              @click="submitOrder"
              >上传图片</el-button
            >
          </div>
        </div>
        <div class="flex-col-8">
          <el-form-item label="属性值" prop="value" required>
            <el-input v-model="submitData.value"></el-input>
          </el-form-item>
        </div>
        <div class="flex-col-8">
          <el-form-item label="价格" prop="price">
            <el-input v-model="submitData.price"></el-input>
          </el-form-item>
        </div>
        <div class="flex-col-8">
          <el-form-item label="排序号" prop="orders">
            <el-input v-model="submitData.orders"></el-input>
          </el-form-item>
        </div>
        <div class="flex-col-8" v-if="!state">
          <el-form-item label="商品名称" prop="goodsId">
            <el-select
              v-model="submitData.goodsId"
              @change="getSpecOptions"
              placeholder="商品名称"
            >
              <el-option
                v-for="item in goodsOptions"
                :key="item.goodsId"
                :label="item.goodsName"
                :value="item.goodsId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="flex-col-8">
          <el-form-item label="商品属性" prop="specId">
            <el-select v-model="submitData.specId" placeholder="属性">
              <el-option
                v-for="item in specOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- <div class="flex-col-8">
            <el-form-item label="所属店铺">
              <el-select v-model="submitData.storeId" placeholder="店铺">
                <el-option
                  v-for="item in storeOptions"
                  :key="item.id"
                  :label="item.storeName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div> -->
        <div class="flex-col-8">
          <el-form-item label="属性状态" prop="status">
            <el-select v-model="submitData.status" placeholder="属性状态">
              <el-option label="禁用" :value="0"></el-option>
              <el-option label="启用" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <div class="inner-container container">
      <div class="filter-container flex-row">
        <div class="flex-col-3 input-box">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入规格"
          ></el-input>
        </div>
        <div class="flex-col-3 input-box">
          <el-input
            v-model="queryParams.goodsName"
            placeholder="请输入商品名"
          ></el-input>
        </div>
        <div class="flex-col-3 input-box">
          <el-select v-model="queryParams.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="btn-box">
          <el-button
            type="primary"
            icon="el-icon-search"
            plain
            @click="search"
            v-permission="{ action: 'view', effect: 'disabled' }"
            >搜索</el-button
          >
          <el-button
            type="success"
            icon="el-icon-edit"
            plain
            @click="addData"
            v-permission="{ action: 'add', effect: 'disabled' }"
            >添加</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            v-permission="{ action: 'delete', effect: 'disabled' }"
            @click="batchDelete"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableData"
        border
        v-loading="loading"
        ref="multipleTable"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :header-cell-style="{
          background: 'var(--primary-color)',
          color: 'var(--text-sidebar-hover-color)',
        }"
      >
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" type="index" label="ID" width="66">
        </el-table-column>
        <el-table-column align="center" prop="storeName" label="所属店铺">
        </el-table-column>
        <el-table-column
          align="center"
          prop="goodsName"
          label="所属商品"
          width="180"
        >
        </el-table-column>
        <el-table-column align="center" prop="typeName" label="所属类型">
        </el-table-column>
        <el-table-column align="center" prop="name" label="所属规格">
        </el-table-column>
        <el-table-column align="center" prop="value" label="规格选项" width="180">
        </el-table-column>
        <el-table-column align="center" label="图片" width="120">
          <template slot-scope="scope">
            <img
              v-if="scope.row.picture"
              style="width: 80px; height: 80px"
              :src="`${$upload_path}/${scope.row.picture}`"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="价格">
        </el-table-column>
        <el-table-column align="center" prop="orders" label="排序号">
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="180"
        >
        </el-table-column>
        <el-table-column align="center" prop="createUser" label="创建者">
        </el-table-column>
        <el-table-column
          align="center"
          prop="updateTime"
          label="修改时间"
          width="180"
        >
        </el-table-column>
        <el-table-column align="center" prop="updateUser" label="操作者">
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{
              scope.row.status === 1 ? '启用' : '禁用'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              plain
              type="primary"
              class="edit"
              icon="el-icon-edit"
              v-permission="{ action: 'update', effect: 'disabled' }"
              @click="editData(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDeleteRow(scope.row.id)"
            >
              <el-button
                plain
                type="danger"
                icon="el-icon-delete"
                slot="reference"
                v-permission="{ action: 'delete', effect: 'disabled' }"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
        <template slot="empty">
          <el-empty :image-size="200" description="暂无数据"></el-empty>
        </template>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getTableData, handleVoidMethod } from '@/api/table'
import { upload } from '@/api/upload'
import {
  storePageQuery,
  insert,
  deleteData,
  update,
} from '@/api/specificationOption'
import { specificationEffectiveOptionsByGoods } from '@/api/specification'
import { typeEffectiveOptions } from '@/api/type'
import { storeGoodsEffectiveOptions } from '@/api/goods'
import { storeEffectiveOptions } from '@/api/store'
export default {
  data() {
    return {
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 0,
          label: '禁用',
        },
        {
          value: 1,
          label: '启用',
        },
      ],
      tableData: [],
      specOptions: [],
      typeOptions: [],
      storeOptions: [],
      goodsOptions: [],
      multipleSelection: [],
      queryParams: {
        storeName: '',
        goodsName: '',
        status: -1,
        page: 1,
        pageSize: 10,
      },
      submitData: {
        goodsId: '',
        specId: '',
        picture: '',
        orders: '',
        status: '',
      },
      rules: {
        typeId: [{ required: true, message: '请输入规格', trigger: 'blur' }],
        specId: [
          { required: true, message: '请选择所属规格', trigger: 'blur' },
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
      },
      total: 0,
      state: false,
      loading: false,
      imageUrl: '',
      currentPage: 1,
      labelPosition: 'right',
      dialogFormVisible: false,
    }
  },
  created() {
    this.getTableData()
    this.getOptions()
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.page = val
      this.getTableData()
    },
    uploadFile(item) {
      this.formData = item.raw // 图片文件
      this.imageUrl = URL.createObjectURL(item.raw) // 图片上传浏览器回显地址
      console.log(this.imageUrl, 'imageUrl')
      console.log(this.formData, 'formData')
    },
    handleRemove() {
      this.imageUrl = ''
      this.formData = null
      console.log(this.formData)
      console.log('QAQ')
    },
    async submitOrder() {
      var formData = new FormData()
      formData.append('file', this.formData) // 照片文件
      const { data: res, code } = await upload(formData)
      if (code === 200) {
        this.$message({ type: 'success', message: '上传成功' })
      } else {
        this.$message({ type: 'error', message: '上传失败' })
      }
      this.submitData.picture = res
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.state
            ? handleVoidMethod(
                this,
                '修改成功',
                '修改失败',
                update(this.submitData),
                this.cancel
              )
            : handleVoidMethod(
                this,
                '添加成功',
                '添加失败',
                insert(this.submitData),
                this.cancel
              )
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleSelectionChange(val) {
      this.multipleSelection = []
      val.forEach((item) => {
        const { id } = item
        this.multipleSelection.push(id)
      })
    },
    handleDeleteRow(id) {
      console.log(id)
      handleVoidMethod(this, '删除成功', '删除失败', deleteData([id]))
    },
    cancel() {
      this.submitData = {}
      this.dialogFormVisible = false
    },
    getTableData() {
      this.loading = true
      getTableData(this, storePageQuery(this.queryParams))
    },
    async getOptions() {
      const { data: typeOptions } = await typeEffectiveOptions()
      this.typeOptions = typeOptions
      const { data: storeOptions } = await storeEffectiveOptions()
      this.storeOptions = storeOptions
      const { data: goodsOptions } = await storeGoodsEffectiveOptions()
      this.goodsOptions = goodsOptions
    },
    async getSpecOptions() {
      const { data: res } = await specificationEffectiveOptionsByGoods(
        this.submitData.goodsId
      )
      this.specOptions = res
    },
    search() {
      this.getTableData()
    },
    addData() {
      this.state = false
      this.imageUrl = ''
      this.submitData = {}
      this.dialogFormVisible = true
    },
    editData(item) {
      this.state = true
      this.submitData = JSON.parse(JSON.stringify(item))
      this.imageUrl = this.submitData.picture ? `${this.$upload_path}/${this.submitData.picture}` : ''
      this.dialogFormVisible = true
    },
    batchDelete() {
      if (this.multipleSelection.length <= 0) {
        return this.$message({ type: 'warning', message: '请选择对象' })
      }
      handleVoidMethod(
        this,
        '删除成功',
        '删除失败',
        deleteData(this.multipleSelection)
      )
    },
  },
}
</script>

<style lang="less" scoped>
.tablelist {
  padding: 10px;
  box-sizing: border-box;
  .filter-container {
    flex-wrap: wrap;
    box-sizing: border-box;
    margin-bottom: 20px;
  }
  .inner-container {
    box-sizing: border-box;
    border-radius: 5px;
    padding: 20px;
    background-color: var(--bg-primary-color);
    transition: var(--tran-01);
  }
  .input-box {
    margin-right: 10px;
  }
}
.el-select {
  width: 100%;
}
/deep/ .el-dialog {
  background: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-dialog__wrapper.father > .el-dialog {
  margin: 0;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
/deep/ .el-dialog__title {
  color: var(--text-normal-color) !important;
  transition: var(--tran-01);
}
/deep/ .el-form-item__label {
  color: var(--text-normal-color) !important;
  transition: var(--tran-01);
}
.el-form {
  display: flex;
  flex-wrap: wrap;
}
/deep/ .el-form-item__label {
  text-align: center !important;
}
.el-pagination {
  margin-top: 20px;
}

/deep/ .el-pagination button {
  background-color: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-pager li {
  background-color: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-pager li.active {
  color: var(--primary-color);
  background-color: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-pagination__total {
  color: var(--text-normal-color);
  transition: var(--tran-01);
}
/deep/ .el-pagination__jump {
  color: var(--text-normal-color);
  transition: var(--tran-01);
}
.btn-box {
  display: flex;
  flex-wrap: wrap;
}
/deep/ .el-button {
  flex-grow: 1;
}
/deep/ .el-input .el-input__inner {
  color: var(--text-normal-color);
  background-color: var(--history-color) !important;
  transition: var(--tran-01);
}

/deep/ .el-select-dropdown {
  background-color: var(--history-color) !important;
}
/deep/ .el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

/deep/ .el-table__body-wrapper.is-scrolling-left::-webkit-scrollbar,
/deep/ .el-table__body-wrapper.is-scrolling-right::-webkit-scrollbar,
/deep/ .el-table__body-wrapper.is-scrolling-middle::-webkit-scrollbar {
  height: 5px;
}
/deep/ .el-table__body-wrapper.is-scrolling-left::-webkit-scrollbar-thumb,
/deep/ .el-table__body-wrapper.is-scrolling-right::-webkit-scrollbar-thumb,
/deep/ .el-table__body-wrapper.is-scrolling-middle::-webkit-scrollbar-thumb {
  background: #ccc; // 滑块颜色
  border-radius: 6px; // 滑块圆角
}
/deep/ .el-table__body-wrapper.is-scrolling-left::-webkit-scrollbar-track,
/deep/ .el-table__body-wrapper.is-scrolling-right::-webkit-scrollbar-track,
/deep/ .el-table__body-wrapper.is-scrolling-middle::-webkit-scrollbar-track {
  border-radius: 10px; // 轨道圆角
  background-color: #fff // 轨道颜色 ;
}
/deep/ .el-table tr {
  color: var(--text-normal-color);
  background-color: var(--history-color);
  transition: var(--tran-01);
}

// /deep/ .el-table .cell {
//   display: flex;
//   align-items: center;
//   justify-content: center;
// }

/deep/ .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden; //多出的隐藏
  //text-overflow: ellipsis;//多出部分用...代替
  display: -webkit-box; //定义为盒子模型显示
  -webkit-line-clamp: 2; //用来限制在一个块元素显示的文本的行数
  -webkit-box-orient: vertical; //从上到下垂直排列子元素（设置伸缩盒子的子元素排列方式）
}

/deep/ .el-table__body tr:hover > td {
  background-color: #a69ff5 !important;
  color: var(--text-sidebar-hover-color);
}

.edit {
  margin-right: 10px;
}

.upload-wrapper {
  display: flex;
  margin-bottom: 10px;
  span {
    width: 100px;
    text-align: end;
    box-sizing: border-box;
    padding-right: 10px;
    display: inline-block;
  }
  .send {
    width: 100%;
    margin-top: 10px;
  }
}

.el-tag {
  margin-right: 10px;
}

/deep/ .el-upload-dragger {
  width: 300px;
  height: 300px;
}
.deleteImg {
  font-size: 20px;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
}
</style>
